package com.qinggeng.project.api.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.qinggeng.common.constant.Constants;
import com.qinggeng.framework.web.domain.AjaxResult;
import com.qinggeng.project.api.dto.GrantBindDTO;
import com.qinggeng.project.api.dto.UserBindGsdDto;
import com.qinggeng.project.api.security.annotation.LoginRequired;
import com.qinggeng.project.api.security.utils.ApiUtils;
import com.qinggeng.project.system.service.ISysConfigService;
import com.qinggeng.project.system.service.UserBindGsdService;
import com.qinggeng.project.tool.third.service.ISysThirdPlatformService;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;

/**
 * @author 吴鹏飞
 * @date 2020/11/23
 */
@Api(tags = "果舒达绑定提现模块")
@RestController
@RequestMapping("${apiPath}/gsdWithdrawal")
public class ApiGsdWithdrawalController {
    @Autowired
    private ISysThirdPlatformService thirdPlatformService;

    @Autowired
    private UserBindGsdService userBindGsdService;

    @Autowired
    private ISysConfigService sysConfigService;


    @ApiOperation("支付宝授权码infoStr")
    @PostMapping("/alipayToAppAuth")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", dataType = "String", name = Constants.TOKEN, value = "token标记", required = true)
    })
    //@LoginRequired
    public AjaxResult alipayToAppAuth(){
        try {
            String platform = "alipayByGsd";
            String alipayCode = thirdPlatformService.alipayToAppAuth(platform);
            return AjaxResult.success("操作成功",alipayCode);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }

    @ApiOperation("提现绑定")
    @PostMapping("/withdrawBind")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "platform", value = "platform(wx,alipay)", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "code",value = "wx是code,alipay是appAuthCode"),
            @ApiImplicitParam(paramType = "header", dataType = "String", name = Constants.TOKEN, value = "token标记", required = true)
    })
    @LoginRequired(role = ApiUtils.DEFAULT_ROLE_USER)
    public AjaxResult aliPayBind(GrantBindDTO grantBindDTO) {
        try {
            if ("wx".equals(grantBindDTO.getPlatform())){
                thirdPlatformService.wxBindByGsd(grantBindDTO.getOpenid(),grantBindDTO.getAccessToken());
            }else if ("alipay".equals(grantBindDTO.getPlatform())){
                thirdPlatformService.alipayBindByGsd(grantBindDTO.getCode());
            }else {
                return AjaxResult.error(grantBindDTO.getPlatform()+"--平台不存在");
            }
            return AjaxResult.success("绑定成功");
        } catch (Exception e) {
            return AjaxResult.success(e.getMessage());
        }
    }
    @ApiOperation("提现解绑")
    @PostMapping("/untie")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "提现id", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(paramType = "header", dataType = "String", name = Constants.TOKEN, value = "token标记", required = true)
    })
    @LoginRequired(role = ApiUtils.DEFAULT_ROLE_USER)
    public AjaxResult untie(Long id) {
        int result = userBindGsdService.untieById(id);
        if (result <=0){
            return AjaxResult.error("解绑失败 ，result="+result);
        }
        return AjaxResult.success("解绑成功");
    }


    @ApiOperation("查询提现绑定信息")
    @PostMapping("/withdrawBindInfo")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", dataType = "String", name = Constants.TOKEN, value = "token标记", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 200,message = "",response = UserBindGsdDto.class)
    })
    @LoginRequired(role = ApiUtils.DEFAULT_ROLE_USER)
    public AjaxResult withdrawBindInfo(){
        //跟据用户Id查询绑定信息
        List<UserBindGsdDto> userBindGsdDtos = userBindGsdService.selectUserBindGsdInfoByUserId(ApiUtils.getUserId());
        //查询微信或支付宝是否提现
        String key = (String) sysConfigService.selectConfigByKey("sys.withdraw.open");
        //解析字符串
        JSONObject jsonObject = JSON.parseObject(key);
        //封装
        HashMap<String, UserBindGsdDto> data = Maps.newHashMap();
        if (userBindGsdDtos !=null && userBindGsdDtos.size()>0){
            //根据平台封装对象

            //微信支付宝都绑定
            if (userBindGsdDtos.size()==2){
                for (UserBindGsdDto userBindGsdDto : userBindGsdDtos) {
                    //wx
                    if (userBindGsdDto.getPlatform().equals("wx")){
                        userBindGsdDto.setOpen(jsonObject.getString("wx"));
                        data.put("wx",userBindGsdDto);
                    }
                    //alipay
                    if (userBindGsdDto.getPlatform().equals("alipay")){
                        userBindGsdDto.setOpen(jsonObject.getString("alipay"));
                        data.put("alipay",userBindGsdDto);
                    }
                }
            }
            //支付宝微信只绑定一个
            if (userBindGsdDtos.size()==1){
                for (UserBindGsdDto userBindGsdDto : userBindGsdDtos) {
                    //绑定了微信
                    if (userBindGsdDto.getPlatform().equals("wx")){
                        userBindGsdDto.setOpen(jsonObject.getString("wx"));
                        data.put("wx",userBindGsdDto);
                        UserBindGsdDto userBindGsdDtoAli = new UserBindGsdDto();
                        userBindGsdDtoAli.setOpen(jsonObject.getString("alipay"));
                        userBindGsdDtoAli.setIsBind("0");
                        data.put("alipay",userBindGsdDtoAli);
                    }
                    //绑定了支付宝
                    if (userBindGsdDto.getPlatform().equals("alipay")){
                        userBindGsdDto.setOpen(jsonObject.getString("alipay"));
                        data.put("alipay",userBindGsdDto);
                        UserBindGsdDto userBindGsdDtoWx = new UserBindGsdDto();
                        userBindGsdDtoWx.setIsBind("0");
                        userBindGsdDtoWx.setOpen(jsonObject.getString("wx"));
                        data.put("wx",userBindGsdDtoWx);
                    }
                }
            }

        }else {
            //如果查询为空,设置新对象,按照平台区分
            UserBindGsdDto userBindDtoGsdWx = new UserBindGsdDto();
            userBindDtoGsdWx.setIsBind("0");
            userBindDtoGsdWx.setOpen(jsonObject.getString("wx"));
            data.put("wx",userBindDtoGsdWx);
            UserBindGsdDto userBindGsdDtoAli = new UserBindGsdDto();
            userBindGsdDtoAli.setIsBind("0");
            userBindGsdDtoAli.setOpen(jsonObject.getString("alipay"));
            data.put("alipay",userBindGsdDtoAli);
        }


        return AjaxResult.success("查询成功",data);
    }

}
